#ifndef MODBUSRTU_H
#define MODBUSRTU_H

#include <QObject>
#include <QTimer>
#include "serialmanager.h"

struct ModbusParams {
    int slaveAddr;
    int startAddr;
    int count;
    QString function;
    QString data;
    int timeout;
    int retryCount;
};

class ModbusRTU : public QObject
{
    Q_OBJECT

public:
    explicit ModbusRTU(SerialManager *serialManager, QObject *parent = nullptr);

    void readData(const ModbusParams &params);
    void writeData(const ModbusParams &params);

signals:
    void responseReady(const QString &response);
    void errorOccurred(const QString &error);

private slots:
    void onDataReady(const QByteArray &data);
    void handleTimeout();

private:
    QByteArray calculateCrc(const QByteArray &data);
    QByteArray buildModbusRequest(const ModbusParams &params);
    QString parseModbusResponse(const QByteArray &response, int expectedCoilCount);
    void startTimeoutMonitoring(int timeout);
    void sendRequest(const QByteArray &request);

    SerialManager *serialManager_;
    QTimer *timeoutTimer_;
    ModbusParams currentParams_;
    QByteArray responseBuffer_;
    bool waitingResponse_ = false;
    int currentRetryCount_ = 0;
    QByteArray lastRequestFrame_;
    int expectedCoilCount_ = 0;
};

#endif // MODBUSRTU_H
